package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.ProjectInfo;
import com.hnichr.ump.common.talent.library.service.ProjectInfoService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class ProjectInfoSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "projectInfoList";

    @Autowired
    private ProjectInfoService projectInfoService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray projectList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(projectList)){
            return;
        }
        for(Object projectObject:projectList){
            if(projectObject instanceof JSONObject){
                JSONObject project = (JSONObject) projectObject;
                ProjectInfo projectInfo = new ProjectInfo();
                projectInfo.setId(project.getString("id"));
                projectInfo.setDelFlag(project.getBoolean("delFlag"));
                projectInfo.setUserId(project.getString("userId"));
                if(project.containsKey("createTime")){
                    projectInfo.setOrginalCreateTime(new Date(project.getLong("createTime")));
                }
                if(project.containsKey("updateTime")){
                    projectInfo.setOrginalUpdateTime(new Date(project.getLong("updateTime")));
                }

                projectInfo.setProjectName(project.getString("projectName"));

                if(project.containsKey("startTime")){
                    projectInfo.setStartTime(new Date(project.getLong("startTime")));
                }

                if(project.containsKey("endTime")){
                    projectInfo.setEndTime(new Date(project.getLong("endTime")));
                }

                projectInfo.setProjectDescribe(project.getString("projectDescribe"));
                projectInfo.setResumeId(project.getString("resumeId"));
                projectInfo.setSyncDate(syncDate);
                projectInfoService.merge(projectInfo);
            }
        }
    }
}
